;(function () {
  var E = window.wangEditor
  var editor = new E('#editor')
  editor.customConfig.zIndex = 100
  editor.customConfig.uploadImgServer = uploadUrl
  editor.customConfig.uploadFileName = 'file'
  editor.customConfig.customAlert = function (info) {}
  editor.customConfig.uploadImgHooks = {
      // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
      // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
      customInsert: function (insertImg, result, editor) {
          // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
          // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
          // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
          var url = result.url
          insertImg(url)
      }
  }
  // editor.txt.html()  读取内容
  // editor.txt.html('<p>用 JS 设置的内容</p>')   设置内容

  new Vue({
    el: '#createHouse',
    data: {
      yxState: {list: [{name: '整租', code: 'ER'}, {name: '工位', code: 'WR'}], active: 'ER'},
      projectList: [],
      projectParams: {id: null, name: null, flag: false},
      buildingList: [],
      buildingParams: {id: null, name: null, flag: false},
      floorList: [],
      floorParams: {id: null, name: null, flag: false},
      unitList: [],
      unitParams: {id: null, name: null, flag: false},
      positinList: [],
      selectedUnitList: [],
      unitIds: [],
      queryUnitParams: {ids: [], list: []},
      wpIds: [],
      wpItem: [],
      queryWpParams: {ids: [], list: []},
      stIds: [],
      stItem: [],
      queryStParams: {ids: [], list: []},
      wpflag: false,
      stflag: false,

      shareTitle: '',
      shareAbstract: '',
      shareImg: '',
      contentTitle: '',
      contentInfo: '',
			recommendFlag: false
    },
    methods: {
			recommendEvent () {
				this.recommendFlag = !this.recommendFlag;
				if (!this.recommendFlag) {
					this.setYxState('ER')
				}
			},
			removeHouse () {				
				this.setYxState('ER')
				this.projectParams = {
				  id: '',
				  name: '',
				  flag: false
				}
				this.recommendFlag = false
			},
			
      // 设置合同工位状态
      setYxState (val) {
        this.yxState.active = val;
        this.queryUnitParams = {ids: [], list: []}
        this.queryWpParams = {ids: [], list: []}
        this.queryStParams = {ids: [], list: []}
        this.stIds = []
        this.stItem = []
        this.wpIds = []
        this.wpItem = []
        this.emptyParams()
      },
      //获取项目
      getProject () {
        hlhttp.get({
          url: 'user/projects',
          success: (res) => {
            this.projectList = res;
          }
        })
      },
      //获取楼宇
      getBuilding () {
        hlhttp.get({
          url: 'project/buildings',
          data: {project_id: this.projectParams.id},
          success: (res) => {
            this.buildingList = res;
          }
        })
      },
      //获取楼层
      getFloor () {
        hlhttp.get({
          url: 'building/floors',
          data: {project_id: this.projectParams.id, building_id: this.buildingParams.id},
          success: (res) => {
            this.floorList = res;
          }
        })
      },
      // 获取单元
      getUnit () {
        hlhttp.get({
          url: 'floor/units',
          data: {project_id: this.projectParams.id, building_id: this.buildingParams.id, floor_id: this.floorParams.id},
          success: (res) => {
            res.map(item => {
              item.buildingName = this.buildingParams.name;
            })
            if (!res.length) return;
            if (!this.wpflag && !this.stflag) {
              this.unitList = filterUnitPosition(res, 'BU', 'unitType');
            }
            if (this.wpflag) {
              this.unitList = filterUnitPosition(res, 'WP', 'unitType');
            }
            if (this.stflag) {
              this.unitList = filterUnitPosition(res, 'ST', 'unitType');
            }
          }
        })
      },
      //获取工位车位
      getPosition () {
        hlhttp.get({
          url: 'units/positions',
          data: {unit_id: this.unitParams.id},
          success: (res) => {
            res.map(item => {
              item.unitId = this.unitParams.id
              item.unitName = this.unitParams.name
              item.buildingName = this.buildingParams.name
              item.floor = this.floorParams.name
              item.buildingId = this.buildingParams.id
              item.floorId = this.floorParams.id
            })
            if (this.wpflag) {
              this.positinList = filterUnitPosition(res, 'WP', 'positionType')
            }
            if (this.stflag) {
              this.positinList = filterUnitPosition(res, 'ST', 'positionType')
            }
          }
        })
      },
      //项目id，name获取
      getProjectParams (ops) {
        if (ops.projectId == this.projectParams.id) return;
        this.projectParams = {id: ops.projectId, name: ops.projectName, flag: false}
        this.queryUnitParams = {ids: [], list: []}
        this.queryWpParams = {ids: [], list: []}
        this.queryStParams = {ids: [], list: []}
        this.stIds = []
        this.stItem = []
        this.wpIds = []
        this.wpItem = []
        this.emptyParams()
      },
      //楼宇id， name获取
      getBuildingParams (ops) {
        this.buildingParams = {id: ops.buildingId, name: ops.name, flag: true}
        if (this.buildingParams.flag) this.getFloor()
      },
      //楼层id， name获取
      getFloorParams (ops) {
        this.floorParams = {id: ops.floorId, name: ops.floorName, flag: true}
        if (this.floorParams.flag) this.getUnit()
      },
      //单元id， name获取
      getunitParams (ops) {
        this.unitParams = {id: ops.unitId, name: ops.unitName, flag: true}
        if (this.unitParams.flag) this.getPosition()
      },
      //显示关闭单元弹窗
      changeProjectFlag () {
        if (!this.projectParams.id) return;
        this.projectParams.flag = !this.projectParams.flag;
        if (this.projectParams.flag) {
          this.getBuilding()
          if (this.queryUnitParams.ids.length) {
            this.selectedUnitList = JSON.parse(JSON.stringify(this.queryUnitParams.list))
            this.unitIds = JSON.parse(JSON.stringify(this.queryUnitParams.ids))
          }
        }
        if (!this.projectParams.flag) {
          this.emptyParams()
        }
      },
      emptyParams () {
        this.buildingParams = {id: null, name: null, flag: false}
        this.floorParams = {id: null, name: null, flag: false}
        this.$refs.building.innerHTML = '请选择'
        this.$refs.floor.innerHTML = '请选择'
        this.$refs.building1.innerHTML = '请选择'
        this.$refs.floor1.innerHTML = '请选择'
        this.$refs.building2.innerHTML = '请选择'
        this.$refs.floor2.innerHTML = '请选择'
        this.$refs.unit.innerHTML = '请选择'
        this.$refs.unit1.innerHTML = '请选择'
        this.buildingList = []
        this.floorList = []
        this.unitList = []
        this.selectedUnitList = []
        this.unitIds = []
        this.positinList = []
      },
      //显示关闭工位弹窗
      changeWpFlag () {
        if (!this.projectParams.id) return;
        this.wpflag = !this.wpflag
        if (this.wpflag) {
          this.getBuilding()
          if (this.queryWpParams.ids.length) {
            const items = JSON.parse(JSON.stringify(this.queryWpParams.list))
            this.wpItem = []
            items.forEach(item => {
              item.children.map(item0 => {
                this.wpItem.push({
                  buildingId: item.buildingId,
                  buildingName: item.buildingName,
                  companyName: item.companyName,
                  contractId: item.contractId,
                  flag: item.flag,
                  floor: item.floor,
                  floorId: item.floorId,
                  positionId: item0.positionId,
                  positionName: item0.positionName,
                  positionType: item.positionType,
                  rentState: item.rentState,
                  rentType: item.rentType,
                  unitId: item.unitId,
                  unitName: item.unitName
                })
              })
            })
            this.wpIds = JSON.parse(JSON.stringify(this.queryWpParams.ids))
          }
        }
        if (!this.wpflag) {
          this.emptyParams()
        }
      },
      //显示关闭车位
      changeStFlag () {
        if (!this.projectParams.id) return;
        this.stflag = !this.stflag
        if (this.stflag) {
          this.getBuilding()
          if (this.queryStParams.ids.length) {
            const items = JSON.parse(JSON.stringify(this.queryStParams.list))
            this.stItem = []
            items.forEach(item => {
              item.children.map(item0 => {
                this.stItem.push({
                  buildingId: item.buildingId,
                  buildingName: item.buildingName,
                  companyName: item.companyName,
                  contractId: item.contractId,
                  flag: item.flag,
                  floor: item.floor,
                  floorId: item.floorId,
                  positionId: item0.positionId,
                  positionName: item0.positionName,
                  positionType: item.positionType,
                  rentState: item.rentState,
                  rentType: item.rentType,
                  unitId: item.unitId,
                  unitName: item.unitName
                })
              })
            })
            this.stIds = JSON.parse(JSON.stringify(this.queryStParams.ids))
          }
        }
        if (!this.stflag) {
          this.emptyParams()
        }
      },
      //选中单元
      selectedUnit (ops) {
        if (this.unitIds.indexOf(ops.unitId) > -1) {
          this.selectedUnitList = toHeavy(this.selectedUnitList, ops.unitId, 'unitId')
          this.unitIds = toFilter(this.unitIds, ops.unitId)
          return
        }
        this.unitIds.push(ops.unitId)
        this.selectedUnitList.push(ops)
      },
      //确认选中的单元
      queryUnit () {
        this.queryUnitParams = {ids: JSON.parse(JSON.stringify(this.unitIds)), list: JSON.parse(JSON.stringify(this.selectedUnitList))}
        this.changeProjectFlag()
      },
      //删除已选单元
      deleteUnit (i) {
        this.queryUnitParams.ids.splice(i, 1);
        this.queryUnitParams.list.splice(i, 1);
      },
      // 选中工位
      selectWpPosition (ops) {
        if (this.wpIds.indexOf(ops.positionId) > -1) {
          this.wpItem = toHeavy(this.wpItem, ops.positionId, 'positionId')
          this.wpIds = toFilter(this.wpIds, ops.positionId)
          return
        }
        this.wpIds.push(ops.positionId)
        this.wpItem.push(ops)
      },
      // 选中车位
      selectStPosition (ops) {
        if (this.stIds.indexOf(ops.positionId) > -1) {
          this.stItem = toHeavy(this.stItem, ops.positionId, 'positionId')
          this.stIds = toFilter(this.stIds, ops.positionId)
          return
        }
        this.stIds.push(ops.positionId)
        this.stItem.push(ops)
      },
      //确认选中的工位
      queryWp () {
        let newArr = hlArrayUtil.removeRepeat(this.wpItem, 'unitId')
        newArr.map(item => {
          item.children = []
        })
        this.wpItem.map(item => {
          newArr.map(item1 => {
            if (item.unitId == item1.unitId) {
              item1.children.push({positionName: item.positionName, positionId: item.positionId})
            }
          })
        })
        this.queryWpParams = {ids: JSON.parse(JSON.stringify(this.wpIds)), list: JSON.parse(JSON.stringify(newArr))}
        this.changeWpFlag()
      },
      //确认选中的车位
      querySt () {
        let newArr = hlArrayUtil.removeRepeat(this.stItem, 'unitId')
        newArr.map(item => {
          item.children = []
        })
        this.stItem.map(item => {
          newArr.map(item1 => {
            if (item.unitId == item1.unitId) {
              item1.children.push({positionName: item.positionName, positionId: item.positionId})
            }
          })
        })
        this.queryStParams = {ids: JSON.parse(JSON.stringify(this.stIds)), list: JSON.parse(JSON.stringify(newArr))}
        this.changeStFlag()
      },
      //删除工位
      deleteWp (i0, i1, id) {
        this.queryWpParams.list[i0].children.splice(i1, 1)
        let ids = this.queryWpParams.ids;
        for (var i = 0; i < ids.length; i++) {
          if (ids[i] == id) {
            ids.splice(i, 1)
          }
        }
        if (!this.queryWpParams.list[i0].children.length) {
          this.queryWpParams.list.splice(i0, 1)
        }
      },
      //删除车位
      deleteSt (i0, i1, id) {
        this.queryStParams.list[i0].children.splice(i1, 1)
        let ids = this.queryStParams.ids;
        for (var i = 0; i < ids.length; i++) {
          if (ids[i] == id) {
            ids.splice(i, 1)
          }
        }
        if (!this.queryStParams.list[i0].children.length) {
          this.queryStParams.list.splice(i0, 1)
        }
      },
      uploadClickimg () {
        $('.imgclick').trigger('click')
      },
      saveHouse () {

        let units = [];
        let stops = [];
        let wps = [];
        let unitIds = [];
        let positionIds = [];
        this.queryUnitParams.list.map(item => {
          unitIds.push(item.unitId)
          units.push({
            "building_id": item.buildingId,
            "building_name": item.buildingName,
            "floor_id": item.floorId,
            "floor_num": item.floor + '',
            "unit_id": item.unitId,
            "unit_name": item.unitName,
            "unit_acreage": item.acreage + '',
          })
        })

        this.queryWpParams.list.map(item => {
          unitIds.push(item.unitId)
          item.children.map(item0 => {
            wps.push({
              "building_id": item.buildingId,
              "building_name": item.buildingName,
              "floor_id": item.floorId,
              "floor_num": item.floor + '',
              "unit_id": item.unitId,
              "unit_name": item.unitName,
              "wp_acreage": '0',
              "wp_id": item0.positionId,
              "wp_name": item0.positionName
            })
            positionIds.push(item0.positionId)
          })
        })

        this.queryStParams.list.map(item => {
          unitIds.push(item.unitId)
          item.children.map(item0 => {
            stops.push({
              "building_id": item.buildingId,
              "building_name": item.buildingName,
              "floor_id": item.floorId,
              "floor_num": item.floor + '',
              "unit_id": item.unitId,
              "unit_name": item.unitName,
              "stop_acreage": '0',
              "stop_id": item0.positionId,
              "stop_name": item0.positionName
            })
            positionIds.push(item0.positionId)
          })
        })

        if (!this.shareTitle) {
          hl.toast('请填写分享标题')
          return
        }
        if (!this.shareAbstract) {
          hl.toast('请填写分享简介')
          return
        }
        if (!this.shareAbstract) {
          hl.toast('请填写分享简介')
          return
        }
        if (!this.recommendFlag) {
        	units = '#'
        	stops = '#'
        	wps = '#'
        }
				if (this.recommendFlag) {
					if (units != '#') {
						wps = '#'
					}
					if (wps != '#') {
						units = '#'
					}
					if (!stops.length) {
						stops = '#'
					}
				}
        if (!this.contentTitle) {
          hl.toast('请填写内容标题')
          return
        }
        if (!editor.txt.html()) {
          hl.toast('请填写内容详情')
          return
        }

        unitIds = hlArrayUtil.arrUnique(unitIds)

        var projectinfo = {
          project_id: !this.recommendFlag ? '#' : this.projectParams.id,
          project_name: !this.recommendFlag ? '#' : this.projectParams.name,
          units: JSON.stringify(units),
          wps: JSON.stringify(wps),
          stops: JSON.stringify(stops),
        };
        hlhttp.put({
          url: 'customer/house_resource',
          data: {
            unit_ids:!this.recommendFlag ? '#' : unitIds.toString(),
            position_ids: !this.recommendFlag ? '#' : positionIds.toString() || '#',
            house_share_id: hlUrlUtil.GetQueryString('id'),
            share_title: this.shareTitle,
            share_introduction: this.shareAbstract,
            share_pic: this.shareImg,
            contract_type: !this.recommendFlag ? '#' : this.yxState.active,
            content_title: this.contentTitle,
            content_detail: editor.txt.html(),
            project_info: JSON.stringify(projectinfo)
          },
          success: () => {
            hl.toast('编辑房源分享成功')
            hlUrlUtil.goTo('houseInfo', {id: hlUrlUtil.GetQueryString('id'), ddtab:true})
          }
        })
      },

      getInfoData () {
        hlhttp.get({
          url: 'customer/house_resource',
          data: {house_share_id: hlUrlUtil.GetQueryString('id')},
          success: (data) => {
            this.shareTitle = data.shareTitle
            this.shareAbstract = data.shareIntroduction
            this.contentTitle = data.contentTitle
            this.shareImg = data.sharePic	
            

            // units
            let units = data.projectInfo.units
            units.map(item => {
              this.queryUnitParams.ids.push(item.unitId)
              this.queryUnitParams.list.push({
                buildingId: item.buildingId,
                buildingName: item.buildingName,
                floorId: item.floorId,
                floor: item.floorNum,
                unitId: item.unitId,
                unitName: item.unitName,
                acreage: item.unitAcreage
              })
            })

            // wps
            let wps = data.projectInfo.wps
            let wpsList = hlArrayUtil.removeRepeat(wps, 'unitId');
            wpsList.map(item => {
              item.floor = item.floorNum
              item.children = []
            })
            wps.map(item => {
              this.queryWpParams.ids.push(item.wpId)
              wpsList.map(item0 => {
                if (item.unitId == item0.unitId) {
                  item0.children.push({positionName: item.wpName, positionId: item.wpId})
                }
              })
            })
            this.queryWpParams.list = wpsList;

            // stops
            let stops = data.projectInfo.stops
            let stopsList = hlArrayUtil.removeRepeat(stops, 'unitId');
            stopsList.map(item => {
              item.floor = item.floorNum
              item.children = []
            })
            stops.map(item => {
              this.queryStParams.ids.push(item.stopId)
              stopsList.map(item0 => {
                if (item.unitId == item0.unitId) {
                  item0.children.push({positionName: item.stopName, positionId: item.stopId})
                }
              })
            })
            this.queryStParams.list = stopsList;
						
						
						if (this.queryUnitParams.list.length || this.queryWpParams.list.length || this.queryStParams.list.length) {
							this.recommendFlag = true
							setTimeout(() => {
								this.$refs.yxProject.innerHTML = data.projectInfo.projectName
								this.projectParams = {id: data.projectInfo.projectId, name: data.projectInfo.projectName, flag: false}
							}, 0)
						}
						
						

            editor.txt.html(data.contentDetail)
          }
        })
      }
    },
    created () {
      hlSelectUi()
    },
    mounted() {
      editor.create()
      this.getProject()
      this.getInfoData()

      imgupload('.imgclick', uploadUrl, (res) => {
        this.shareImg = res.json.url
      })
    }
  })

  function filterUnitPosition (arr, type, key) {
    let newArr = [];
    arr.forEach(item => {
      if (item[key] == type) {
        item.flag = false;
        newArr.push(item)
      }
    })
    return newArr
  }
} ())
